﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Deeper.Common;
namespace Deeper.Engine
{

	public class Variable : IElement
	{
		public Document Host { protected set; get; }
		public string Name { protected set; get; }
		public object DataSource { protected set; get; }

		public Variable(Document host, string name)
		{
			if (name.IsNull()) throw new Exception("变量名称不可为空");
			Host = host;
			Name = name;
		}

		protected object GetDatasource()
		{
			object obj = null;
			IList<string> list = null;
			int postion = Name.IndexOf('.');
			if (postion > 0)
			{
				list = Name.Split('.').Where(s => s.Length > 0).ToList();
				obj = Host.Items[list[0]] ?? null;
				if (obj.IsNull())
					throw new Exception("变量名错误");
				obj = obj.GetSubPropertyValue(Name.Substring(postion + 1));
			}
			else
			{
				obj = Host.Items[Name] ?? null;
				if (obj.IsNull())
					throw new Exception("变量名错误");
			}
			return obj;
		}

		public void Render(System.IO.TextWriter writer)
		{
			if (DataSource.IsNull())
				DataSource = GetDatasource();
			writer.Write(DataSource.ToString());
		}

		public override string ToString()
		{
			if (DataSource.IsNull())
				DataSource = GetDatasource();
			return DataSource.ToString();
		}


	}
}
